<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  layout: 'tabbar',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
}
</route>

<template>
  <!--  #ifdef MP-WEIXIN -->
  <open-screen />
  <!--  #endif -->
  <view class="relative" v-if="showIndex">
    <z-paging 
      ref="pagingRefs" 
      v-model="dataList" 
      :default-page-size="10"
      :safe-area-inset-bottom="true"
      :refresher-complete-delay="500"
      @onRefresh="onRefresh"
      @query="queryList"
    >
      <template #top>
        <!--  #ifdef MP-WEIXIN -->
        <view class="w-full"
          :style="{ paddingTop: common.menuTop - 17 + 'px' }"
        ></view>
        <!--  #endif -->
      </template>
      <template #bottom>
        <view class="w-full h-50px"></view>
      </template>
      
      <view class="relative">
        <!-- 轮播图 -->
        <my-swiper :list="bannerList" />

        <!-- 邀请好友 -->
        <view class="w-259rpx h-78rpx absolute right--12rpx bottom--30rpx flex-center z-999" 
          style="pointer-events: none;"
          v-if="isShowShare"
        >
          <image class="gzh-icon" mode="widthFix" :src="icons.red_packet"></image>
          <view class="shakeX absolute left-28rpx top-14rpx">
            <i class="iconfont icon-Frame1 inline-block color-#fff"></i>
          </view>
          <view class="absolute left-0 top-0 w-full h-full" style="pointer-events: visible;">
            <wd-button v-if="user.userInfo.gzhFlag" custom-class="share-btn" open-type="share">分享</wd-button>
            <wd-button v-else custom-class="share-btn" @click="handleToGzh">去关注公众号</wd-button>
            <!-- <view class="absolute right-24rpx top-19rpx h-40rpx w-40rpx z-9" @click.stop="isShowShare = false"></view> -->
          </view>
        </view>
      </view>

      <!-- 标题 -->
      <base-title text="今日缘分推荐" wrapClass="pb-20rpx" />
      <!-- 每日推荐列表 -->
      <daily-list ref="dailyListRefs" />
      
      <view class="w-696rpx m-a pt-14rpx">
        <!-- <view class="border-1px"></view> -->
      </view>

      <!-- 年龄段选择 -->
      <view class="age-list w-center flex-sb-center pt-10rpx relative">
        <view 
          class="age-item w-142rpx h-64rpx flex-center font-size-44rpx color-#9C6DEF rounded-full leading-0" 
          v-for="(item, index) in generationList.showList"
          :key="item.id"
          @click="changeAge(item.typeCode)"
          :class="{ 
            'age-active': item.typeCode === currentAge,
          }"
        >
          <text>
            <text>{{ getName(item.typeName) || '--' }}</text>
            <text class="font-size-22rpx">后</text>
          </text>
        </view>
        <view 
          v-if="generationList.hideList.length"
          class="box-border relative w-70rpx h-64rpx flex-center font-size-28rpx color-#9C6DEF rounded-full leading-0 bg-#F0E7FF"
          @click="changeAge('')"
          :class="{ 
            'age-active': generationList.hideTypeCodeList.includes(currentAge), 
          }"
        >更多</view>
        <view 
          class="popover position-b-r !-bottom-12rpx w-145rpx rounded-8rpx pt-12rpx pb-12rpx pl-6rpx pr-6rpx bg-white z-10"
          :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
          v-if="isShowPopover"
        >
          <block
            v-for="(item, index) in generationList.hideList"
            :key="item.id"
          >
            <view 
              class="text-center font-size-22rpx leading-32rpx mb-8rpx mt-8rpx color-#9C6DEF" 
              :class="{ 'font-bold': currentAge === item.typeCode }"
              @click="changeAge(item.typeCode)"
            >
              <text 
                :class="[
                  {'font-size-44rpx': item.typeName !== '不限'},
                  {'font-size-28rpx': item.typeName === '不限'},
                ]"
              >{{ getName(item.typeName) || '--' }}</text>
              <text v-if="item.typeName !== '不限'">后</text>
            </view>
            <view class="border-2px" v-if="(index+1) !== generationList.hideList.length"></view>
          </block>
        </view>
      </view>
      
      <!-- 搜索条件 -->
      <index-search 
        ref="searchRefs"
        searchWrapClass='pl-20rpx pr-20rpx' 
        :pagination="pagination"
        :filterStr="filterStr"
        @handleChange="handleChange"
        @handleClear="handleClear"
        @handleFilter="toFilter" 
        @handleConfirm="handleSearchConfirm"
        @handleSearch="handleSearchConfirm"
      />
      
      <!-- tab选项 -->
      <view class="w-center pt-6rpx">
        <base-tabs 
          :tab="gender" 
          :tabList="enumParams.genderList" 
          :address="city"
          @changeTab="changeTab" 
          @show-city="toSelectAddress" 
        />
      </view>

      <!-- 个人信息卡片列表 -->
      <view class="w-center pt-20rpx">
        <!-- 骨架屏 -->
        <view class="w-center pt-20rpx" v-if="isFirst">
          <view class="person-item bg-white p-20rpx mb-20rpx"
            :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
            v-for="item in 3" 
            :key="item" 
          >
            <view style="display: flex;">
              <wd-skeleton 
                animation="gradient" 
                :custom-style="{ width: '100%', marginRight: '12px' }" 
                :row-col="[{ width: '100%' }, { width: '50%' }, { width: '30%' }]" 
              />
              <wd-skeleton animation="gradient" :row-col="[{ size: '200rpx', type: 'rect' }]" />
            </view>
            <wd-skeleton 
              animation="gradient" 
              :custom-style="{ marginTop: '12px' }" 
              theme="text" 
            />
          </view>
        </view>
        
        <!-- 加载中 -->
        <view class="flex-center py-50rpx" v-if="!isFirst && loading">
          <wd-loading size="32rpx" color="#9C6DEF" />
        </view>

        <person-item
          v-for="item in dataList"
          :key="item.id"
          :data="item"
          :isShowDistrictName="isShowDistrictName"
        />
      </view>
    </z-paging>
    
    <view class="w-750rpx m-a px-32rpx fixed left-0 bottom-50px box-border flex-sb-center" 
      style="background: rgba(27,27,27,0.66);"
      :style="{ 
        bottom: safeBottom + 50 + 'px', 
        paddingTop: !(isShowLive && common.liveStreamingConfig.liveStreamingFlag) ? 0 : '20rpx',
        paddingBottom: !(isShowLive && common.liveStreamingConfig.liveStreamingFlag) ? 0 : '20rpx',
      }"
    >
      <view class="w-428rpx h-58rpx rounded-full bg-#FF902C flex-center absolute right-0 top--69rpx"
        @click="toPath({ path: '/activity/info' })"
      >
        <view class="shakeX inline-flex">
          <i class="iconfont icon-Frame1 inline-block color-#fff"></i>
        </view>
        <view class="inline-block color-#F5F5F5 font-size-30rpx ml-12rpx">点这里，免费发布征婚信息</view>
      </view>

      <block v-if="isShowLive && common.liveStreamingConfig.liveStreamingFlag">
        <view class="absolute right-12rpx top-12rpx w-28rpx h-28rpx flex-center font-size-24rpx color-#fff" @click="isShowLive = false">
          <i class="iconfont icon-close"></i>
        </view>

        <view class="relative">
          <base-img-box :size="64" :round="64" imgSrc="" />
          <view class="live w-64rpx h-28rpx leading-0 flex-center font-size-18rpx bg-#986DF0 rounded-4rpx color-#fff">直播中</view>
        </view>

        <view class="w-400rpx color-#fff font-size-32rpx">
          <!-- <view>真诚相亲的进 正在直播</view> -->
          <view class="font-size-28rpx">进直播间 免费相亲匹配</view>
        </view>

        <view class="w-132rpx bg-linear-7 rounded-56rpx h-48rpx bg-#986DF0 flex-center color-#fff leading-0 font-size-28rpx mr-12rpx">
          去看看
        </view>
      </block>
    </view>
  </view>
</template>

<script lang="ts" setup>
import BaseTitle from "@/components/base/base-title.vue";
import BaseTabs from "@/components/base/base-tabs.vue";
import MySwiper from "@/components/swiper/my-swiper.vue";
import PersonItem from "@/components/list-item/person-item.vue";
import DailyList from "@/components/list-item/daily-list.vue";
import IndexSearch from "@/components/search/index-search.vue";
import BaseImgBox from "@/components/base/base-img-box.vue";
import OpenScreen from "@/components/open-screen.vue";
import { enumParams, share } from '@/enum/index';
import { useThemeStore, useUserStore } from "@/store";
import { GetCarouselBannerInfo } from "@/service/db_index";
import { Main } from "@/service/types";
import { useCommonStore } from '../../store/common';
import { GetUserPage } from "@/service/db_user";
import { useToast } from "wot-design-uni";
import { deepClone } from "wot-design-uni/components/common/util";
import { icons } from '@/utils/icons'

// 主题颜色
const { themeConfig } = useThemeStore();
const common = useCommonStore();
const user = useUserStore();
const isShowLive = ref(true);
const toast = useToast();
const isShowShare = ref(true);

/** 获取用户直播配置表详情 */
common.getLiveStreamingConfig();

const isShowDistrictName = computed(() => {
  return common.commonState.addressInfo.cityId == pagination.cityId;
})

const toPath = (item) => {
  if (!user.isLogined) {
    uni.navigateTo({ url: '/pages/login/index' });
    return
  }
  
  // if (item.path === '/activity/info' && user.userInfo.matchmakerFlag) {
  //   toast.show('您已注册为红娘,不可再填写资料！');
  //   return
  // }

  uni.navigateTo({ url: item.path })
}

/**
 * 请求payload参数
 */
const pagination = reactive<AnyObj>({});
const dataList = ref([]);
const pagingRefs = ref();
const isFirst = ref(true);
const loading = ref(false);
const queryList = async (pageNo, pageSize) => {
  try {
    loading.value = true;
    const { data } = await GetUserPage(pagination, {
      pageNum: pageNo,
      pageSize,
    });
    isFirst.value = false;
    loading.value = false;
    const list = data.records || [];
    pagingRefs.value.complete(list);
  } catch (error) {
    loading.value = false;
    pagingRefs.value.complete(false);
    isFirst.value = false;
  }
}

defineOptions({
  name: 'Home',
})

const getName = computed(() => {
  return (name: string) => {
    if (name === '不限') return name;
    const [_name, ...other] = name.split('后');
    return _name
  }
})

/** 获取年代列表 */
const generationList = computed(() => {
  const list = deepClone(common.commonState.dictInfo['generation']) || [];
  list.push({
    id: 18646813547,
    typeCode: 'none',
    typeName: '不限',
  })
  const showList = list.filter((item, index) => index <= 3) || [];
  const hideList = list.filter((item, index) => index > 3) || [];
  
  // 用于给 更多按钮的 判断
  const hideTypeCodeList = hideList.map(item => item.typeCode);
  return {
    showList, // 显示的四个年代
    hideList, // 气泡显示的年代
    hideTypeCodeList
  }
})

// 性别筛选
const gender = ref<string>('');
const changeTab = (typeCode) => {
  setGender(typeCode);

  const filterList = filterStr.value.split(',');
  const gender = typeCode ? typeCode == '0' ? '男' : '女' : '';
  if (filterList.includes('男')) {
    filterStr.value = filterList.map(item => item === '男' ? gender : item).filter(item => !!item).join(',');
  }
  if (filterList.includes('女')) {
    filterStr.value = filterList.map(item => item === '女' ? gender : item).filter(item => !!item).join(',');
  }
  
  pagingRefs.value.reload();
}
// 设置性别
const setGender = (typeCode) => {
  gender.value = typeCode;
  pagination.gender = typeCode;
}
// 如果自动筛选当前相反性别
const genderAutoFilter = () => {
  const userProfileInfoVo: any = user.userInfo.userProfileInfoVo || {};
  if (userProfileInfoVo.gender) {
    const gender = userProfileInfoVo.gender == '0' ? '1' : '0';
    setGender(gender);
  }
}

// 筛选条件确认
const handleFilterSubmit = (data = {}) => {
  Object.assign(pagination, data);
  pagingRefs.value.reload();
}

// 搜索框
const handleSearchConfirm = (keyword) => {
  pagination.code = keyword;
  pagingRefs.value.reload();
}
const handleChange = (code) => {
  pagination.code = code;
}

const searchRefs = ref();
const handleClear = () => {
  for (const key in pagination) {
    // if (['gender'].includes(key)) continue;
    delete pagination[key];
  }
  filterStr.value = '';
  city.value = '全国';
  currentAge.value = '';
  gender.value = '';
  pagingRefs.value.reload();
  nextTick(() => {
    searchRefs.value.resetValue();
  })
}

// 轮播图数据列表
const bannerList = ref<Main.CarouselBannerInfo[]>([]);
/**
 * 获取轮播图
 */
const getCarouselBannerInfo = async () => {
  try {
    const res = await GetCarouselBannerInfo({});
    res.data.forEach(item => {
      const { 
        fileInfoVo = {} as typeof item.fileInfoVo 
      } = item || {};
      item.preUrl = fileInfoVo.preUrl || '';
    })
    bannerList.value = res.data || [];
  } catch (error) {
    console.log('error', error)
  }
}
getCarouselBannerInfo();

const isShowPopover = ref(false) // 是否显示剩余年龄段的气泡框
const currentAge = ref('') // 当前选中的年龄段
const timer = ref(null); // 3秒后关闭年龄段弹窗
const changeAge = (typeCode = '') => {
  if (!isShowPopover.value && typeCode === '') {
    timer.value = setTimeout(() => {
      isShowPopover.value = false;
    }, 3000)
  }

  if (timer.value && isShowPopover.value) {
    clearTimeout(timer.value);
    timer.value = null;
  }
  // 点击更多，显示或隐藏剩余年龄段
  if (typeCode === '') {
    isShowPopover.value = !isShowPopover.value;
    return
  }
  // 隐藏剩余年龄段的气泡框
  isShowPopover.value = false;
  // 当前选中的年龄段相同，不触发事件
  if (currentAge.value === typeCode) return;
  // 更新选中的年龄段
  currentAge.value = typeCode;

  pagination.generation = typeCode === 'none' ? '' : typeCode;
  pagingRefs.value.reload();
}

const onRefresh = () => {
  nextTick(() => {
    dailyListRefs.value.reLoadList();
  })
}

// 跳转到公众号引导页面
const handleToGzh = () => {
  if (!user.isLogined) {
    uni.navigateTo({ url: '/pages/login/index' });
    return
  }
  uni.navigateTo({
    url: '/feature/follow',
  })
}

const city = ref('全国');
// 去选择地区页面
const toSelectAddress = () => {
  const { provinceId, cityId, districtId } = pagination || {};
  const list = [provinceId, cityId, districtId].filter(item => !!item);
  uni.navigateTo({
    url: '/feature/areaPicker?type=1&page=Index&areaStr=' + list.join(','),
  })
}

// 更新城市
function handleUpdateArea(data) {
  if (!data) {
    city.value = '全国';
    Object.assign(pagination, {
      provinceId: undefined, 
      cityId: undefined, 
      districtId: undefined
    })
    setTimeout(() => {
      pagingRefs.value.reload();
    }, 100)
    return
  }
  
  const [valStr, labelStr] = data.split('/');
  const [provinceVal, cityVal, districtVal] = valStr.split(',');
  const labelList = labelStr.split(',');
  
  city.value = labelList.join('');
  Object.assign(pagination, {
    provinceId: provinceVal, 
    cityId: cityVal, 
    districtId: districtVal
  })
  setTimeout(() => {
    pagingRefs.value.reload();
  }, 100)
}

// 去筛选页面
const toFilter = () => {
  uni.navigateTo({
    url: '/feature/filter?data=' + JSON.stringify(pagination)
  })
}

// 根据地区id获取地区名称
const getCityName = (data) => {
  const { provinceId, cityId, districtId } = data || {};
  const list = common.commonState.regionInfo || [];
  const provinceItem = list.find(item => item.id == provinceId) || { name: '', children: [] };
  const cityItem = provinceItem.children.find(item => item.id == cityId) || { name: '', children: [] };
  const districtItem = cityItem.children.find(item => item.id == districtId) || { name: '' };

  const cityList = [provinceItem.name, cityItem.name, districtItem.name].filter(item => !!item);
  if (cityList[0] == cityList[1]) {
    cityList.shift();
  }
  return cityList.join('');
}

const filterStr = ref('');
// 更新筛选条件
function handleUpdateFilter(data) {
  const _data = JSON.parse(data);
  const { filterData, formStr } = _data || {};
  filterStr.value = formStr;
  for (const key in pagination) {
    pagination[key] = undefined;
  }
  Object.assign(pagination, filterData);
  if (!pagination.provinceId) {
    city.value = '全国'
  } else {
    city.value = getCityName(pagination);
  }
  gender.value = filterData.gender;
  setTimeout(() => {
    pagingRefs.value.reload();
  }, 100)
}

// 获取地址
const getAddress = () => {
  const { 
    provinceId, cityId, districtId,
    city: _city, district
  } = common.commonState.addressInfo || {};
  city.value = _city;
  Object.assign(pagination, { provinceId, cityId });
  // pagingRefs.value.reload();
}

// 获取屏幕边界到安全区域距离
const safeBottom = ref(0);
const dailyListRefs = ref();
const showIndex = ref(false);
onLoad(() => {
  uni.$on('updateAreaIndex', handleUpdateArea);
  uni.$on('indexUpdateFilter', handleUpdateFilter);
  
  // genderAutoFilter();
  if (!common.hasAddress) {
    common.addressCallback.push(getAddress);
  } else {
    getAddress();
  }
  
  nextTick(() => {
    const { safeAreaInsets } = uni.getSystemInfoSync();
    safeBottom.value = safeAreaInsets.bottom || 0;
  })

  setTimeout(() => {
    showIndex.value = true;
  }, 0)
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$off('updateAreaIndex', handleUpdateArea);
  uni.$on('indexUpdateFilter', handleUpdateFilter);
})

onShow(() => {
  user.userInfo.id && user.getUserInfo();
  if (user.loginSubmit) {
    user.loginSubmit = false;
    // genderAutoFilter();
    setTimeout(() => {
      dailyListRefs.value && dailyListRefs.value.reLoadList();
      pagingRefs.value.reload();
    }, 100)
  }
})

// 是否关注公众号
const gzhFlag = computed(() => {
  return user.userInfo.gzhFlag;
})

// 分享
onShareAppMessage(() => {
  const { id = '', userProfileInfoVo } = user.userInfo || {};
  const { partnerRequirements, personalImageryInfoVoList = [] } = userProfileInfoVo || {};
  const firstItem = personalImageryInfoVoList[0] || { fileInfoVo: { preUrl: '' } };
  const _fileInfoVo = firstItem.fileInfoVo || { preUrl: '' };
  
  const params = {
    instrId: id || '',
    source: gzhFlag.value ? 'gzh' : '',
  }
  let paramsStr = '';
  for (const key in params) {
    paramsStr += `${key}=${params[key]}&`
  }
  
  const sharePath = `/pages/tabbar/index?${paramsStr}`;
  console.log('sharePath: ', sharePath);
  return {
    title: '我满心期待，与你相遇的未来！',
    path: sharePath,
    imageUrl: share
  }
})
</script>

<style lang="scss" scoped>
// 年龄段选择 start
.age-item {
  @apply box-border relative;
  border: 3rpx solid #986DF0;
}
.age-active {
  color: #fff;
  border: none;
  background: linear-gradient( 180deg, #9C6DEF 0%, #E5C4FF 100%);
}
.popover {
  border: 3rpx solid #986DF0;
}
// 年龄段选择 end

// 轮播图高度
:deep(.wd-swiper__track) {
  height: 408rpx !important;
}

.live {
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translate(-50%, 20%);
  z-index: 9999;
}

@keyframes shakeX {
  from,
  to{
    transform: translate3d(0, 0, 0);
  }

  50% {
    transform: translate3d(-16rpx, 0, 0);
  }
}

.shakeX{
  animation-name: shakeX;
  animation-duration: .5s;
  animation-iteration-count: infinite;
}
</style>
